import { history, } from 'umi';
import routesConfig, { RouteItem } from '@/config/routes-config';
import {
  Model,
  updateState,
  addTabs,
  deleteTabs,
  clearTabs,
} from '@/utils/dva-helper';
// import Action from '@/Action';

// 初始化Model层
export class GlobalState {
  selectKeys: string[] = [];

  openKeys: string[] = [];

  currentRoute: RouteItem | null = null;

  tabRoutes: RouteItem[] = [];

  currUrl: string = '';

  companyId: number = 0;
}

const MODEL_NAME = 'global';
const model: Model<GlobalState> = {
  namespace: MODEL_NAME,
  state: new GlobalState(),
  // 订阅
  subscriptions: {
    // 路由事件订阅
    routerChange: ({ dispatch, history: _history }) =>
      _history.listen(() => {
        // let currentRoute: null | RouteItem = null;
        let currentRoute: any;
        // 获取当前路由所映射的配置
        for (const i in routesConfig) {
          const routeItem = routesConfig[i];
          const permission = history?.location?.state;
          if (routeItem.path === history.location.pathname) {
            currentRoute = {
              ...routeItem,
              query: history?.location?.query,
              permission,
            };
            break;
          }
        }
        const menunames = currentRoute?.menuname || [];
        // // 更新路由信息
        dispatch({
          type: 'updateState',
          payload: {
            openKeys: menunames.slice(-2),
            selectKeys: menunames.slice(-1),
            currentRoute,
          },
        });
        dispatch({
          type: 'addTabs',
          payload: { ...currentRoute },
        });
      }),
    // microAPP({ dispatch }): any {
    //   Action.onGlobalStateChange((state: any) => {
    //     console.log('state', state);
    //     const { microUrl } = state;
    //     dispatch({
    //       type: 'changeCurrUrl',
    //       payload: {
    //         currUrl: microUrl,
    //       },
    //     });
    //   }, true);
    // },
  },
  effects: {},
  reducers: {
    // 通用更新
    updateState,
    addTabs,
    deleteTabs,
    clearTabs,
    changeCurrUrl(state, { payload }) {
      return {
        ...state,
        currUrl: payload.currUrl,
      };
    },
  },
};
export default model;
